package com.ruoyi.web.controller.common;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Date;

/**
 * sse实现服务端消息推送
 * */
@RestController
@RequestMapping("/sse")
public class sseController {
    @Log(title="消息发送", businessType = BusinessType.OTHER)
    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @GetMapping("/sub")
    public SseEmitter sseEmitter(){
        SseEmitter emitter =new SseEmitter();
        new Thread(()->{
            try{
                //向客户端发送数据
                emitter.send(SseEmitter.event().name("message").data("SSE 服务端发送数据"));
                Thread.sleep(1000);
                emitter.complete();
            }catch (IOException  e){
                // 发生错误时
                emitter.completeWithError(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }).start();

        return emitter;
    }

}
